package com.hxgz.steel.util;

import com.hxgz.steel.common.ServerResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 上传图片文件
 */
@RestController
public class UploadPic {
    private Logger logger = LoggerFactory.getLogger(UploadPic.class);

    /**
     * 获取上传文件在服务器中的地址
     * @param multipartFile
     * @return
     */
    public  String upload( MultipartFile multipartFile){
        int status=0;
        FileOutputStream stream = null;
        String filePath = "";
        try {
            String fileName = multipartFile.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            String fileSuffix = fileName.substring(index);
            byte[] bytes = multipartFile.getBytes();
            fileName = DigestUtils.md5Hex(bytes) + fileSuffix;
            filePath = PropertiesUtil.getProperty("ftp.server.http.prefix")+PropertiesUtil.getProperty("ftp.server.imgPath")+System.currentTimeMillis()+ fileName;
            File img = new File(filePath);
            if(!img.getParentFile().exists()){
                img.getParentFile().mkdirs();
            }
            stream = new FileOutputStream(img);
            stream.write(bytes);
            stream.close();
        } catch (IOException e) {
            status++;
            e.printStackTrace();
            ServerResponse.createByErrorMessage("上传失败，请重试！");
        } finally {
            try {
                if (stream != null){
                    stream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(status>0){
            return null;
        }else {
            return filePath;
        }

    }
}
